from django.http import HttpResponse
from django.shortcuts import render
from Utils.stringlib import CONFIG,LNG
from Typelab.settings import BASE_DIR
from Utils.utils import Controller
import os
import json
def reset(request):
    return HttpResponse("reset")
def install(request):
    return HttpResponse("install")
def init(request):
    GET = request.GET
    if GET.__contains__('share/commonJs'):
        return render(request, "Explorer/user/commonJsexplorerindex.js")

    try:
        _path = GET['name']


        path, default,state = Controller.get_data_base_dir()

        cpath = BASE_DIR + "/Typelab/dss_config.json"
        ipath = BASE_DIR + '/Typelab/initDataDirectory'


        assert os.path.exists(ipath), "Data destructed"

        idirectory = os.path.abspath(_path)
        assert os.path.exists(idirectory), "Directory not exist"

        tj = os.listdir(idirectory)
        assert tj.__len__() == 0,"Need a blank Directory!"

        cfg = {}
        if os.path.exists(cpath):
            tf = open(cpath, 'r')
            cfg = json.loads(tf.read())
            tf.close()
        else:
            cfg['DataPath'] = '__NULL__'
        assert os.path.abspath(idirectory) != os.path.abspath(cfg['DataPath']), "strange,same with old one!"

        if not os.path.exists(idirectory):
        #空目录时继续
            os.mkdir(idirectory)

        from shutil import copytree, copy2

        for d in os.listdir(ipath):
            if os.path.isdir(ipath + '/' + d):
                copytree(ipath + '/' + d, idirectory + '/' + d)
            else:
                copy2(ipath + '/' + d, idirectory + '/' + d)
        cfg.update({"DataPath":idirectory.replace('\\','/')})
        tf = open(cpath,'w')
        tf.write(json.dumps(cfg))
        tf.close()
    except Exception as e:
        return Controller.show_json(str(e), state=False)
        pass
    return Controller.show_json('init success,Plz refresh', state=True)
#基于信任不检查
    installTag = BASE_DIR + "/Data/system/install"
    if GET.__contains__('operation'):
        operation = GET['operation']
        if operation=='reset':
            pass
        elif operation == 'install':
            return Controller.show_json(True)

def index(request):
    DataDirectory,Default,state=Controller.get_data_base_dir()

    operator = 'install'
    operation = "Install"
    msg = "Plz install first"
    qpath = DataDirectory if DataDirectory is not None else "___NULL___"
    if os.path.exists(qpath):
        operator = "reset"
        operation = "Reset"
        msg = ""

    context = {
        "config": CONFIG
        , "lng": LNG
        ,'msg':msg
        , 'operator': operator
        , "operation": operation
        ,"defaultDretory":Default if DataDirectory is None else DataDirectory
    }
    return render(request,"System/index.html",context)